﻿using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace FormDesigner
{
    public partial class ListEditorForm : Form
    {
        public ListEditorForm()
        {
            InitializeComponent();
        }

        private void btnNewList_Click(object sender, EventArgs e)
        {
            string CleanedText = tbListName.Text.Trim();
            if (CleanedText == "New List Name" || CleanedText == "" || CleanedText == null)
            {
                MessageBox.Show("You did not enter a List Name! This is required.");
                return;
            }

            dgvListForms.Rows.Clear();
            tbListName.Text = CleanedText;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            dgvListForms.Rows.Clear();
        }

        private string addFormToGrid(string fromFile)
        {
            string formName = string.Empty;

            dgvListForms.DataSource = null;

            DataSet dsSet = new DataSet();
            dsSet.ReadXml(fromFile);

            DataTable tables = dsSet.Tables["form"];

            foreach (DataRow thisRow in tables.Rows)
            {
                DataGridViewRow newRow = new DataGridViewRow();
                if (thisRow["display"].ToString().Length > 0 && thisRow["name"].ToString().Length > 0)
                {
                    // We ignore the default entry.
                    if (thisRow["name"].ToString().Contains("default"))
                    {
                        formName = thisRow["display"].ToString();
                        continue;
                    }

                    newRow.CreateCells(dgvListForms, new string[] { thisRow["display"].ToString(), thisRow["name"].ToString() });
                    dgvListForms.Rows.Add(newRow);
                    newRow.Selected = true;
                }
            }
            return formName;
        }

        private void btnLoadList_Click(object sender, EventArgs e)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter = "Form List (.xml)|FormList.xml";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.FileName = "FormList.xml";
            openFileDialog1.InitialDirectory = Application.StartupPath;

            openFileDialog1.Multiselect = false;
            openFileDialog1.CheckFileExists = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
            {
                if (MessageBox.Show("Any unsaved changed will be lost. Are you sure?", "Load Form?", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                dgvListForms.Rows.Clear();
                string formName = addFormToGrid(openFileDialog1.FileName);
                if (formName != string.Empty)
                {
                    tbListName.Text = formName;
                }
                else
                {
                    MessageBox.Show("Default entry not found. Error in form list.");
                }
            }
        }

        private void btnSaveList_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.AddExtension = true;
            dialog.FileName = "FormList";
            dialog.Filter = "XML files (*.xml)|*.xml";
            dialog.OverwritePrompt = true;

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("Error Saving Form List or No Filename Given!");
                return;
            }

            string FileName = dialog.FileName;
            dialog.Dispose();

            if (tbListName.Text.ToString().Length == 0)
            {
                MessageBox.Show("Error: You must fill out the Default Name field above the Save button.");
                return;
            }
            try
            {
                XmlDocument dom = new XmlDocument();
                XmlDeclaration decl = dom.CreateXmlDeclaration("1.0", "utf-8", null);
                dom.AppendChild(decl);
                XmlElement Root = dom.CreateElement("Forms");

                XmlElement elem = dom.CreateElement("form");
                elem.SetAttribute("display", tbListName.Text.ToString());
                elem.SetAttribute("name", "default");
                Root.AppendChild(elem);

                foreach (DataGridViewRow thisRow in dgvListForms.Rows)
                {
                    if (thisRow.Cells[0].Value == null || thisRow.Cells[1].Value == null)
                        continue;
                    if (thisRow.Cells[0].Value.ToString().Length != 0)
                    {
                        if (thisRow.Cells[1].Value.ToString().Length != 0)
                        {
                            elem = dom.CreateElement("form");
                            elem.SetAttribute("display", thisRow.Cells[0].Value.ToString());
                            elem.SetAttribute("name", thisRow.Cells[1].Value.ToString());
                            Root.AppendChild(elem);
                        }
                    }
                }

                dom.AppendChild(Root);
                dom.Save(FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            return;
        }
    }
}
